package com.ruoyi.mdkt.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.mdkt.entity.Student;
import com.ruoyi.mdkt.entity.Teacher;
import com.ruoyi.mdkt.entity.WXAuth;
import com.ruoyi.mdkt.entity.WXUserInfo;
import com.ruoyi.mdkt.entity.vo.LoginVo;
import com.ruoyi.mdkt.entity.vo.RegistVo;
import com.ruoyi.mdkt.entity.vo.WxVo;
import com.ruoyi.mdkt.service.*;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.service.ISysUserRoleService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.security.auth.login.LoginContext;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserLoginServiceImpl implements UserLoginService {


    @Value("${wx.appid}")
    private String appid;
    @Value("${wx.secret}")
    private String secret;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private WXService wxService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private SysLoginService sysLoginService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private PetService petService;
    @Autowired
    private ISysUserRoleService userRoleService;


    @Override
    public R getSessionId(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code";
        String replaceUrl = url.replace("{0}", appid).replace("{1}", secret).replace("{2}", code);
        String s = HttpUtils.sendGet(replaceUrl);
        System.out.println(s);
        WxVo wxVo = JSON.parseObject(s, WxVo.class);
        LoginVo loginVo = new LoginVo();
        if (s!=null) {
            String s1 = sysLoginService.wxLogin(wxVo.getOpenid());
            if (s1 != null) {
                loginVo.setIsFirstLogin(0);
                loginVo.setToken(sysLoginService.wxLogin(wxVo.getOpenid()));

            } else {
                SysUser user = new SysUser();
                user.setOpenId(wxVo.getOpenid());
                user.setUserName(wxVo.getOpenid());
                user.setNickName("无名氏");
                int i = sysUserService.insertUser(user);
                if (i > 0) {
                    loginVo.setIsFirstLogin(1);
                    loginVo.setToken(sysLoginService.wxLogin(wxVo.getOpenid()));
                    if (!petService.newPet(sysUserService.selectUserByIdOpenid(wxVo.getOpenid()).getUserId())){
                        return R.fail("创建宠物失败");
                    }
                } else {
                    return R.fail("创建用户失败");
                }
            }
        } else {
            return R.fail("微信登录出错！");
        }

        return R.ok(loginVo);
    }

    @Override
    public R authLogin(WXAuth wxAuth) throws InvalidAlgorithmParameterException, NoSuchPaddingException, IllegalBlockSizeException, UnsupportedEncodingException, NoSuchAlgorithmException, BadPaddingException, InvalidKeyException {
        String s = wxService.wxDecrypt(wxAuth.getEncryptedData(), wxAuth.getSessionId(), wxAuth.getIv());
        WXUserInfo wxUserInfo = JSON.parseObject(s, WXUserInfo.class);
        String openId = wxUserInfo.getOpenId();
        LambdaQueryWrapper<Student> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Student::getOpenId, openId);
        LambdaQueryWrapper<Teacher> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper1.eq(Teacher::getOpenId, openId);
        Student student = studentService.getOne(lambdaQueryWrapper);
        Teacher teacher = teacherService.getOne(lambdaQueryWrapper1);
        if (student == null & teacher == null) {
            student.setOpenId(openId);
            student.setName(wxUserInfo.getNickname());

        } else if (teacher != null) {
        }
        Map<String, Object> map = new HashMap<>();
        map.put("userinfo", s);
        map.put("token", "token");
        return R.ok(s);
    }

    @Override
    public R regist(RegistVo registVo, Long userId) {
        SysUser sysUser = sysUserService.selectUserById(userId);
        if (sysUser == null){
            return R.fail("用户不存在");
        }
        sysUser.setNickName(registVo.getNickName());
        sysUser.setSex(registVo.getSex());
        sysUser.setEmail(registVo.getEmail());
        sysUser.setPhonenumber(registVo.getPhonenumber());
        int i = sysUserService.updateUser(sysUser);
        if (i < 1){
            return R.fail("用户信息插入失败");
        }



        if (registVo.getRole() == 0){
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(userId);
            sysUserRole.setRoleId(101L);
            Boolean aBoolean = userRoleService.insertUserRole(sysUserRole);
            if (!aBoolean){
                return R.fail("用户角色插入失败");
            }
            Student student = new Student();
            student.setUserId(userId);
            student.setName(registVo.getNickName());
            student.setOpenId(registVo.getOpenId());
            student.setStudentId(registVo.getTsId());
            boolean save = studentService.save(student);
            if (!save){
                return R.fail("保存学生信息失败");
            }
        }else if (registVo.getRole() == 1){
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(userId);
            sysUserRole.setRoleId(100L);
            Boolean aBoolean = userRoleService.insertUserRole(sysUserRole);
            if (!aBoolean){
                return R.fail("用户角色插入失败");
            }
            Teacher teacher = new Teacher();
            teacher.setUserId(userId);
            teacher.setName(registVo.getNickName());
            teacher.setOpenId(registVo.getOpenId());
            teacher.setTeacherId(registVo.getTsId());
            boolean save = teacherService.save(teacher);
            if (!save){
                return R.fail("保存老师信息失败");
            }
        }

        return R.ok();
    }

}
